<?php

namespace Api\Controller;

use Think\Controller;
use User\Api\UserApi;
class UserController extends Controller {
	public function login() {
		$username = I ( 'username', '', 'text' );
		$password = I ( 'password', '', 'text' );
		if ($username == '' && $password == '') {
			$this->ajaxReturn ( array (
					'state' => 601,
					'msg' => '参数不全',
					'data' => NULL 
			) );
			exit ();
		}
		$type = 1;
		if (preg_match ( '/^\d+$/', $username )) {
			// 全数字
			if (preg_match ( '/^(0|86|17951)?(13[0-9]|15[012356789]|17[0678]|18[0-9]|14[57])[0-9]{8}$/', $username )) {
				// 手机号
				$type = 3;
			} else {
				// uid
				$type = 4;
			}
		} else {
			if (preg_match ( '/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/', $username )) {
				// 邮箱
				$type = 2;
			} else {
				// 用户名
				$type = 1;
			}
		}
		$api = new UserApi ();
		$result = $api->login ( $username, $password, $type );
		if ($result > 0) {
			$this->ajaxReturn ( array (
					'state' => 200,
					'msg' => '登录成功',
					'data' => array (
							'uid' => $result 
					) 
			) );
		} else {
			if ($result == - 1) {
				$this->ajaxReturn ( array (
						'state' => 404,
						'msg' => '用户不存在',
						'data' => NULL 
				) );
			}
			if ($result == - 2) {
				$this->ajaxReturn ( array (
						'state' => 401,
						'msg' => '密码错误',
						'data' => NULL 
				) );
			}
		}
	}
	
	public function register(){
		$username = I ( 'username', '', 'text' );
		$nickname = I ( 'nickname', '', 'text' );
		$password = I ( 'password', '', 'text' );
		$email = I ( 'email', '', 'text' );
		$mobile = I ( 'mobile', '', 'text' );
		$nickname = '';
		$api = new UserApi ();
		$result = $api->register($username, $nickname, $password, $email, $mobile);
		if ($result > 0){
			$this->ajaxReturn ( array (
				'state' => 200,
				'msg' => '注册成功',
				'data' => array (
					'uid' => $result
				)
			));
		}else{
			$this->ajaxReturn(array(
					'state' => 500,
					'msg' => '注册失败',
					'data' => NULL
			));
		}
	}
}